<?php

namespace app\api\controller;

use app\common\controller\Api;

use app\common\controller\Frontend;
use app\common\logic\Dao;
use app\common\logic\Wework;
use app\common\logic\SendMessage;
use app\common\model\School;
use app\admin\model\school\Department;
use app\admin\model\student\Student;
use app\admin\model\student\Parents;
use think\Db;
use think\Session;
use app\common\logic\Haikang;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }



    /**
     * 域名地址校验
     */
    public function check()
    {
        import('weworkapi_php-master/callback/WXBizMsgCrypt', EXTEND_PATH, '.php');
        $encodingAesKey = config('wework.EncodingAESKey');
        $token = config('wework.Token');
        $corpId = config('wework.corpId');


        $sVerifyMsgSig = $this->request->param('msg_signature');
        $sVerifyTimeStamp = $this->request->param('timestamp');
        $sVerifyNonce = $this->request->param('nonce');
        $sVerifyEchoStr = $this->request->param('echostr');

        // 需要返回的明文
        $sEchoStr = "";

        $wxcpt = new \WXBizMsgCrypt($token, $encodingAesKey, $corpId);
        $errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);

        if ($errCode == 0) {
//            var_dump($sEchoStr);
            //
            // 验证URL成功，将sEchoStr返回
            echo ($sEchoStr);
        } else {
            print("ERR: " . $errCode . "\n\n");
        }
    }










    /**
     * 通讯录同步
     * 企业微信的推送加密消息有两种，对应的解密方式也有两种，但是文档并没有说明，这两种加密消息是推送到同一url上的，
     * 目前只能通过先转换xml消息，判断 ToUserName 是 SuiteID  还是 corpId
     * 如果是 SuiteID
     * @return array|string
     */
    public function receive()
    {
//         return$this->validateUrl();
        $params = $this->request->param();
        $params['xml'] = $this->request->getInput();


        $procedure[] = ['接收到参数'=>$params];

        $result = false;
        try {
            $xlm = toXml($params['xml']);
            if ($xlm['ToUserName'] != config('wework.corpId')) {
                exit();
            }

            $result = Wework::decodeXml($params['msg_signature'],$params['timestamp'],$params['nonce'],$params['xml']);
            $procedure[] = ['接收到参数-结果'=>$result,'errCode'=>Wework::$errCode];
        } catch (\Exception $e) {
            $procedure[] = ['发生错误'=>$e->getMessage(),'line'=>$e->getLine(),'file'=>$e->getFile()];
        }

        logs($procedure,'receive','','call_cmd/');
        if ($result) {
            return  $result;
        }else{
            exit();
        }

    }


    //验证url
    private function validateUrl()
    {
        $params = $this->request->param();
        $params['xml'] = $this->request->getInput();
        $procedure[] = ['接收到参数'=>$params];


        $result = false;
        try {
            $result = Wework::decodeUrl($params['msg_signature'],$params['timestamp'],$params['nonce'],$params['echostr']);
            $procedure[] = ['接收到参数-结果'=>$result,'errCode'=>Wework::$errCode];
        } catch (\Exception $e) {
            $procedure[] = ['发生错误'=>$e->getMessage(),'line'=>$e->getLine(),'file'=>$e->getFile()];
        }

        logs($procedure,'验证URL');
        if ($result) {
            return  $result;
        }else{
            exit();
        }
    }




    /**
     * 指令回调
     * 应用安装会回调
     */
    public function call_cmd()
    {
        //url 验证
        //return $this->validateUrl();

        $procedure = [];
        $msg = $this->receive();//消息解密
        $procedure[] = ['开始处理数据'=>$msg];

        Db::startTrans();
        try {
            //快速响应
            // $this->response();

            /**
             * 第三方应用 传 InfoType 内部应用传 Event
             *  array (
            'ToUserName' => 'ww3ec564e6f293a9e7',
            'FromUserName' => 'sys',
            'CreateTime' => '1625486396',
            'MsgType' => 'event',
            'Event' => 'change_external_tag',
            'ChangeType' => 'create',
            'Id' => 'etJpWIEAAAjUqPNoyKYgRmXpPNDbgeQQ',
            'TagType' => 'tag',
            )
             *
             * array (
            'SuiteId' => 'ww5fedeee0fedc03b1',
            'AuthCorpId' => 'ww3ec564e6f293a9e7',
            'InfoType' => 'change_school_contact',
            'TimeStamp' => '1625486396',
            'ChangeType' => 'create_department',
            'Id' => '309',
            )
             */
            if (isset($msg['Event'])) {
                switch ($msg['Event']) {
                    //推送suite_ticket（每十分钟）
                    case 'suite_ticket':
                        cache('suite_ticket',$msg['SuiteTicket']);
                        break;
                    //授权成功通知
                    case 'create_auth':
                        //1、获取永久授权码（和授权对象信息）
                        $AuthInfo = Wework::getAuthCode($msg['AuthCode']);
                        $res =  School::add($AuthInfo);

                        break;
                    //变更授权通知
                    case 'change_auth':
                        logs($data,'change_auth','param');
                        break;
                    //取消授权通知
                    case 'cancel_auth':
                        logs($data,'cancel_auth','param');
                        $info = \app\common\model\School::where('corpid',$body['AuthCorpId'])->find();
                        if ($info) {
                            $info->usable = 2;
                            $info->save();
                        }
                        break;
                    //部门变更事件
                    //成员变更事件
                    case 'change_school_contact':
                        //创建部门
                        if ($msg['ChangeType'] == 'create_department') {
                            (new Dao)->addDepartment($msg['Id']);
                        }



                        //更新部门
                        if ($msg['ChangeType'] == 'update_department'){
                            (new Dao)->refreshDepartment($msg['Id']);
                        }

                        //删除部门
                        if ($msg['ChangeType'] == 'delete_department'){
                            $procedure[] = ['删除部门'=>'OK'];
                            (new Dao())->deleteDepartment($msg['Id']);
                        }


                        //创建学生
                        if ($msg['ChangeType'] == 'create_student'){
                            $procedure[] = ['添加学生'=>'OK'];
                            (new Dao)->addStudent($msg['Id']);
                        }

                        //编辑学生
                        if ($msg['ChangeType'] == 'update_student'){
                            $procedure[] = ['刷新学生信息'=>'OK'];
                            (new Dao)->refreshStudent($msg['Id']);
                        }

                        //删除学生
                        if ($msg['ChangeType'] == 'delete_student'){
                            $procedure[] = ['删除学生' => $msg['Id']];
                            Student::where(['student_userid'=>$msg['Id']])->delete();
                        }


                        //创建家长
                        if ($msg['ChangeType'] == 'create_parent'){
                            $procedure[] = ['创建家长信息'=>'OK'];
                            (new Dao)->refreshParent($msg['Id']);
                        }


                        //编辑家长
                        if ($msg['ChangeType'] == 'update_parent'){
                            $procedure[] = ['更新家长信息'=>'OK'];
                            (new Dao)->refreshParent($msg['Id']);
                        }

                        //删除家长
                        if ($msg['ChangeType'] == 'delete_parent'){
                            $procedure[] = ['删除家长' => $msg];
                        }



                        //家长关注事件
                        if ($msg['ChangeType'] == 'subscribe'){
                            $parents = Wework::schoolUserGet(Wework::getAccessToken(), $msg['Id']);
                            $procedure[] = ['家长关注事件' => $parents];
                        }

                        break;
                        //成员变更事件-通讯录（非家校通讯录）
                    case 'change_contact':
                        (new Dao())->bookUser($msg);
                        break;
                    //未知事件
                    default:
                        return false;
                        break;
                }
            }

            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            $procedure[] = ['发生错误'=>$e->getMessage(),'line'=>$e->getLine(),'file'=>$e->getFile()];
        }
        ppp($procedure);
        logs($procedure,'call_cmd');

    }





    //同步通讯录部门(非家校通讯录)
    public function department()
    {
        $result = false;
        Db::startTrans();
        $Dao = new \app\common\logic\Dao();
        try {
            $result = $Dao->departmentListGet();
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            $this->error('系统错误','',$e->getMessage());
        }

        if ($result !== true) {
            Db::commit();
            $this->error($result,'',$Dao->result);
        }else{
            $this->success('更新成功');
        }
    }



    //同步成员(非家校通讯录)
    //获取部门-使用部门id获取部门成员
    public function userlist()
    {
        $result = false;
        Db::startTrans();
        $Dao = new \app\common\logic\Dao();
        try {
            $Dao->userList();
            Db::commit();
        } catch (\Throwable $e) {
            dump($e->getLine());
            dump($e->getFile());
            Db::rollback();
            $this->error('系统错误','',$e->getMessage());
        }

        if ($result !== true) {
            Db::commit();
            $this->error($result,'',$Dao->result);
        }else{
            $this->success('更新成功');
        }
    }


    //同步人员部门负责人信息
    public function userlead()
    {
        $result = false;
        $page = $this->request->get('page/d',1);
        Db::startTrans();
        $Dao = new \app\common\logic\Dao();
        try {
            $Dao->userlead($page);
            Db::commit();
        } catch (\Throwable $e) {
            dump($e->getLine());
            dump($e->getFile());
            Db::rollback();
            $this->error('系统错误','',$e->getMessage());
        }

        if ($result !== true) {
            Db::commit();
            $this->error($result,'',$Dao->result);
        }else{
            $this->success('更新成功');
        }
    }







    //同步年级信息
    public function grade()
    {
        $result = false;
        Db::startTrans();
        $Dao = null;
        try {
            $Dao = new \app\common\logic\Dao();
            $res = $Dao->refreshDepartment();


            die;
            //腾讯标准年级限定-高中
            
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            $this->error('系统错误','',$e->getMessage());
        } finally {
            unset($Dao);
        }

    }











    /**
     * 快速响应 success
     * @method   respone
     * @Author   admin@fyang.vip
     * @DateTime 2021-04-01T11:06:59+0800
     * @return   [type]                   [description]
     */
    private function response($msg = 'success')
    {
        set_time_limit(0);
        ob_end_clean();
        header("Connection: close");
        header("HTTP/1.1 200 OK");
        header("Content-Type: text/html;charset=utf-8");
        ob_start();
        echo $msg;
        $size = ob_get_length();
        header("Content-Length: $size");
        ob_end_flush();
        flush();
        //fastcgi_finish_request(); // 响应完成, 立即返回到前端,关闭连接
        ignore_user_abort(true);// 在关闭连接后，继续运行php脚本
        set_time_limit(0);
    }




    public function test()
    {
        do{
            logs('这是一个测试消息','','','test/');
            sleep(60);
        } while (date('H') < 19);
    }
}
